package com.cctc.rds.raft.core.client.election;

import com.cctc.rds.raft.core.RaftCluster;
import com.cctc.rds.raft.core.log.LogService;
import com.cctc.rds.raft.core.rpc.RpcClientRouter;
import com.cctc.rds.raft.core.rpc.election.ElectionListener;
import com.cctc.rds.raft.core.rpc.election.ElectionRpc;
import com.cctc.rds.raft.core.rpc.election.ElectionRpcScheduler;
import com.cctc.rds.raft.core.rpc.election.impl.ElectionFunctionImpl;
import com.cctc.rds.raft.core.rpc.heartbeat.HeartBeatListener;

public class RaftElectionStarter implements HeartBeatListener {
    private int nodeId;
    private LogService logService;
    private RpcClientRouter<ElectionRpc> router;
    private ElectionRpcScheduler.ElectionFunction electionFunction;
    private ElectionRpcScheduler electionRpcScheduler;

    public RaftElectionStarter(int nodeId, LogService logService, RpcClientRouter<ElectionRpc> router, ElectionListener electionListener) {
        this.nodeId = nodeId;
        this.logService = logService;
        this.router = router;
        this.electionFunction = new ElectionFunctionImpl(nodeId, logService, router, electionListener);
        this.electionRpcScheduler = new ElectionRpcScheduler(electionFunction, RaftCluster.getConfig().getElectionMs());
        RaftCluster.holdHeartBeatListener(this);
        this.electionRpcScheduler.start();
    }

    @Override
    public void onHeartBeat() {
        electionRpcScheduler.reset();
    }

    public void stop() {
        electionRpcScheduler.stop();
        ((ElectionFunctionImpl) electionFunction).close();
    }
}
